package ch.usi.da.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey Karakovskiy, sergey at idsia dot ch
 * Date: Nov 10, 2009
 * Time: 6:26:07 PM
 * Package: ch.usi.da.tcp
 */
public class Client
{
    public void run(int portNumber)
    {
        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            echoSocket = new Socket("localhost", portNumber);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    echoSocket.getInputStream(), "UTF-8"));
            char[] buf = new char[4096];
            in.read(buf);
            System.out.println("in.read() = " + buf[0] + buf[1] + buf[2]);

            out.println("I  am  Echo");
            out.println("reset -lt 0");
            String userInput = "01000";

            String s = null;
            while (true) {
                in.read(buf);
                s = new String(buf);
                for (int i = 3; i < s.length(); ++i)
                {
                    if (s.charAt(i) != 0)
                        System.out.println("echo: " + s);
                }
                out.println(userInput);
            }
//            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

        } catch (UnknownHostException e) {

            System.err.println("Don't know about host given");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to host given.");
            System.exit(1);
        } finally
        {
            out.close();

//            stdIn.close();
            try
            {
                echoSocket.close();
                in.close();
            } catch (IOException e)
            {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
}
